package com.example.administrator.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class ChooseActivity extends AppCompatActivity {
    private ListView mListView;
    private String[] mItems;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose);
        mListView = (ListView) findViewById(R.id.lv_choose);
        mItems = getResources().getStringArray(R.array.listview_menus);
        //单选
     /*   ArrayAdapter<CharSequence> adapter =
                ArrayAdapter.createFromResource(this,R.array.listview_menus,android.R.layout.simple_list_item_single_choice);*/
        ArrayAdapter<CharSequence> adapter =
                ArrayAdapter.createFromResource(this,R.array.listview_menus,android.R.layout.simple_list_item_multiple_choice);
        //设置选择模式 CHOICE_MODE_SINGLE：单选  CHOICE_MODE_MULTIPLE:多选
         mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        //关联适配器
        mListView.setAdapter(adapter);
    }
    public void doClick(View v){
        switch (v.getId()){
            case R.id.bt_choose:
                //单选
//                int i = mListView.getCheckedItemPosition();
//                Toast.makeText(this,mItems[i],Toast.LENGTH_SHORT).show();
                //多选
                StringBuffer result = new StringBuffer();
                //返回所有的选中项
                SparseBooleanArray array = mListView.getCheckedItemPositions();
                for (int i = 0; i < mItems.length; i++)
                {
                    //如果这个选项选是选中的
                    if(array.get(i))
                    {
                        result.append(mItems[i]+"   ");
                    }
                }
                Toast.makeText(ChooseActivity.this, result.toString(), Toast.LENGTH_SHORT).show();
                break;
        }
    }
}
